package com.natalia.file.config;

import com.natalia.file.service.impl.minio.BaseMinioClient;
import io.minio.MinioAsyncClient;
import io.minio.MinioClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Optional;

/**
 * @Author yang
 **/
@Configuration
public class MinioConfig {

    @Resource
    FileProperties minioProperties;

    @Bean
    public MinioClient minioClient(){
        if (existConfig()){
            return MinioClient.builder()
                    .endpoint(minioProperties.getEndpoint())
                    .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                    .build();
        }
        return null;
    }

    /**
     * 配置用于分片上传的Minio连接客户端
     */
    @Bean
    public BaseMinioClient customMinioClient() {
        if (existConfig()){
            MinioAsyncClient asyncClient = MinioAsyncClient.builder()
                    .endpoint(minioProperties.getEndpoint())
                    .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                    .build();
            return new BaseMinioClient(asyncClient);
        }
        return null;
    }

    private  boolean existConfig(){
       return Arrays.asList(
                Optional.ofNullable(minioProperties.getEndpoint()),
                Optional.ofNullable(minioProperties.getAccessKey()),
                Optional.ofNullable(minioProperties.getSecretKey())
        ).stream().allMatch(Optional::isPresent);
    }

}
